<template>
  <el-dialog v-model="visible" :title="title" width="1000" show-footer show-zoom resize :close-on-click-modal="false"
    :close-on-press-escape="false" @close="close">
    <template #default>
      <el-form ref="formRef" :rules="rules" :model="form" label-align="right" label-width="120" size="default"
        label-position="top">
        <el-row :gutter="20">
          <el-col :span="8" v-if="handleType != 'add'">
            <el-form-item label="借样单号" prop="location_code">
              {{ form.product_borrow_sample_order_no }}
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouse_id">
              <SelectWarehouse class="w-full" v-model="form.warehouse_id" :disabled="form.id"></SelectWarehouse>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="审批单号" prop="verify_order_no" v-if="handleType != 'add' || handleType != 'edit'">
              <el-input v-model="form.verify_order_no" placeholder="请输入审批单号" :disabled="handleType == 'view'" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <vxe-table :data="form.detail" :round="true" height="300" :row-class-name="rowClassName">
        <vxe-column title="SKU">
          <template #default="{ row }">
            <template v-if="handleType == 'add' || handleType == 'edit'">
              <el-input v-model="row.sku" placeholder="输入SKU" @change="changeSkU(row)" />
            </template>
            <template v-else>
              {{ row.sku }}
            </template>
          </template>
        </vxe-column>
        <vxe-column title="货位">
          <template #default="{ row }">
            <template v-if="handleType == 'add' || handleType == 'edit'">
              <el-select class="w-full" v-model="row.location_id" placeholder="货位" @change="changeLocation($event, row)">
                <el-option v-for="item in row.location" :key="item.location_id" :label="item.location_code"
                  :value="item.location_id">
                </el-option>
              </el-select>
            </template>
            <template v-else>
              {{ row.location_code }}
            </template>
          </template>
        </vxe-column>
        <vxe-column title="货主">
          <template #default="{ row }">
            <select-personnel v-model="row.owner_id" placeholder="货主" :disabled="handleType == 'view'"></select-personnel>
          </template>
        </vxe-column>
        <vxe-column title="申请数量">
          <template #default="{ row }">
            <template v-if="handleType == 'add' || handleType == 'edit'">
              <el-input v-model="row.apply_num" placeholder="申请数量" />
            </template>
            <template v-else>
              {{ row.apply_num }}
            </template>
          </template>
        </vxe-column>
        <vxe-column title="出库数量" v-if="handleType == 'out' || handleType == 'view'">
          <template #default="{ row }">
            <el-input v-model="row.submit_out_warehouse_num" placeholder="出库数量" :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column title="已出库数量" v-if="handleType == 'out' || handleType == 'view'">
          <template #default="{ row }">
            {{ row.out_warehouse_num }}
          </template>
        </vxe-column>
        <vxe-column title="归还数量" v-if="handleType == 'back' || handleType == 'view'">
          <template #default="{ row }">
            <el-input v-model="row.submit_need_back_num" placeholder="出库数量" :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column title="待归还数量" v-if="handleType == 'back' || handleType == 'view'">
          <template #default="{ row }">
            {{ row.need_back_num }}
          </template>
        </vxe-column>
        <vxe-column field="remark" title="备注">
          <template #default="{ row }">
            <el-input v-model="row.remark" placeholder="备注" :disabled="handleType == 'view'" />
          </template>
        </vxe-column>
        <vxe-column field="opearn" title="操作" width="100" v-if="handleType != 'view'">
          <template #default="{ row, rowIndex }">
            <el-link class="mr-2" size="small" type="primary" @click="addRow">新增</el-link>
            <el-link size="small" type="danger" @click="deleteRow(rowIndex)">删除</el-link>
          </template>
        </vxe-column>
      </vxe-table>
    </template>

    <template #footer>
      <template v-if="handleType == 'view'">
        <div class="flex justify-center py-2">
          <el-button type="" @click="close">关 闭</el-button>
        </div>
      </template>
      <div class="flex justify-center py-2" v-else-if="handleType == 'out'">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="out(formRef)">出库</el-button>
      </div>
      <div class="flex justify-center py-2" v-else-if="handleType == 'back'">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="back(formRef)">归还</el-button>
      </div>
      <div class="flex justify-center py-2" v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save(formRef)">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { getProductBorrowDetail, saveProductBorrow, updateProductBorrow, backProductBorrow, outProductBorrow } from '../api/index'
import { getSKULocation } from '@/api/public'
import { reactive, ref, toRaw, toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import SelectWarehouse from '@/components/SelectWarehouse'


const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(['query'])

const props = defineProps({
  wareDataList: {
    type: Array,
    default: [],
  },
})

const data = reactive({
  form: {},
  title: '新增',
  handleType: null,
  rules: {
    warehouse_id: [{
      required: true, message: '请选择仓库', trigger: 'blur'
    }],
    verify_order_no: [{
      required: true, message: '请输入审批单号', trigger: 'blur'
    }],
  },
})
const { form, title, handleType, rules } = toRefs(data)

const statusMap = new Map([
  ['add', '新增'],
  ['edit', '编辑'],
  ['view', '查看'],
  ['out', '出库'],
  ['back', '归还'],
])

const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  form.value = getForm()
}
// 初始化
const getForm = () => {
  return {
    detail: [
      {
        sku: "",//sku
        custom_sku: "",//自定义sku
        base_sku_code: "",//商品编码
        apply_num: '',//调拨数量
        location_id: "",//货位编码
        remark: "",//备注
        location: []
      }
    ]
  }
}

onMounted(() => {
  initForm()
})

const getDetail = async (id) => {
  try {
    const res = await getProductBorrowDetail({
      id
    })
    form.value = res.data
  } catch (e) {
    throw Error(e)
  }
}

const addRow = async () => {
  form.value.detail.push({
    sku: "",//sku
    custom_sku: "",//自定义sku
    base_sku_code: "",//商品编码
    location_id: null,//货位id
    apply_num: '',//申请数量
    remark: "",//备注
    location: []
  })
}

const rowClassName = ({ row }) => {
  if (row.is_del  === 1) {
    return "hidden-row";
  }
  return '';
}

const deleteRow = (index) => {
  if (form.value.detail.length <= 1) return
  if(handleType.value == 'add'){
    form.value.detail.splice(index, 1)
  }else{
    form.value.detail[index].is_del = 1
  console.log(form.value.detail)

  }
}

const changeSkU = async (row) => {
  if (!row.sku) {
    ElMessage.error('输入sku')
    return
  }
  if (!form.value.warehouse_id) {
    ElMessage.error('请选择调出仓')
    return
  }
  try {
    const res = await getSKULocation({
      sku: row.sku,
      warehouse_id: form.value.warehouse_id,
      type: 1
    })
    row.sku = res.data.sku
    row.location = res.data.location
    row.custom_sku = res.data.custom_sku || '32323sses'
    row.sku_cn_title = res.data.sku_cn_title
    row.base_sku_code = res.data.base_sku_code
  } catch (e) {
    throw Error(e)
  }
}

const changeLocation = (val, row) => {
  // const checkItem = row.origin_location.find(item => item.location_id == val)
  // if (checkItem == undefined) return
  // row.origin_num = checkItem.num
}


const save = () => {
  if (!formRef.value) return
  formRef.value.validate((valid) => {
    if (valid) {
      loading.value = true

      if (form.value.id) {
        const data = toRaw(form.value)
        data.detail = data.detail.map(i => {
          const { _X_ROW_KEY, ...rest } = i;
          return {
            id: rest.id,//产品借样单明细id
            sku: rest.sku,//sku
            custom_sku: rest.custom_sku,//自定义sku
            base_sku_code: rest.base_sku_code,//商品编码
            location_id: rest.location_id,//货位id
            owner_id: rest.owner_id, //货主id
            apply_num: rest.apply_num,//申请数量
            remark: rest.remark,//备注
            is_del: rest.is_del
          }
        })
        updateProductBorrow(data)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        saveProductBorrow(form.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits('query')
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    }
  })
}
const out = async () => {
  let formData = {}
  formData.id = form.value.id
  formData.detail = form.value.detail.map(i => {
    return {
      id: i.id,
      submit_out_warehouse_num: i.submit_out_warehouse_num
    }
  })
  try {
    const res = await outProductBorrow(formData)
    ElMessage.success(res.message)
    emits('query')
    close()
  } catch (e) {
    throw Error(e)
  }
}
const back = async () => {
  let formData = {}
  formData.id = form.value.id
  formData.detail = form.value.detail.map(i => {
    return {
      id: i.id,
      submit_need_back_num: i.submit_need_back_num
    }
  })
  try {
    const res = await backProductBorrow(formData)
    ElMessage.success(res.message)
    emits('query')
    close()
  } catch (e) {
    throw Error(e)
  }
}
const close = () => {
  initForm()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped>
.borderNone {
  :deep(.el-input__wrapper) {
    border: none;
    box-shadow: none
  }
}

</style>

